﻿jQuery.extend({
    selectChain: function(target_id, url, name_field, value_field, appendDataBoundItems, selected_value) {
        var _options = '';
        var _jquery_target_id = '#' + target_id;

        if (appendDataBoundItems) {
            if (jQuery(_jquery_target_id).data("pre_options") == undefined) {
                jQuery(_jquery_target_id).data("pre_options", jQuery(_jquery_target_id).html());
            }
            _options += jQuery(_jquery_target_id).data("pre_options");
        }

        jQuery.ajax({
            type: "GET",
            url: url,
            dataType: "json",
            success: function(j) {
                for (var i = 0; i < j.length; i++) {
                    _name = eval('j[i].' + name_field);
                    _value = eval('j[i].' + value_field);
                    if (_value == selected_value)
                        _options += '<option value="' + _value + '" selected="selected" >' + _name + '</option>';
                    else
                        _options += '<option value="' + _value + '">' + _name + '</option>';
                }
                jQuery(_jquery_target_id).html(_options).change();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                jQuery(_jquery_target_id).html(_options);
            }
        });
    }
});